package com.java.tree;

/**
 * 实现一个简单的 TrieTree
 *
 * @author 19252
 * @date 2020/10/23
 */
public class Trie {

    /**
     * 空的头结点
     */
    private TrieTree root = new TrieTree();

    /**
     * Initialize your data structure here.
     */
    public Trie() {

    }


    /**
     * Inserts a word into the trie.
     */
    public void insert(String word) {
        TrieTree temp = this.root;
        int index;
        for (int i = 0; i < word.length(); i++) {
            index = word.charAt(i) - 97;
            if (temp.getTrieTrees()[index] == null) {
                temp.getTrieTrees()[index] = new TrieTree(word.charAt(i));
            }
            // 向后移动
            temp = temp.getTrieTrees()[index];
        }
        // 字符存入结束，标识以该字符结尾
        temp.setEnd(true);
    }

    /**
     * Returns if the word is in the trie.
     */
    public boolean search(String word) {
        TrieTree temp = this.root;
        int index;
        for (int i = 0; i < word.length(); i++) {
            index = word.charAt(i) - 97;
            if (temp.getTrieTrees()[index] == null) {
                // 字符不匹配，或长度不匹配
                return false;
            }
            temp = temp.getTrieTrees()[index];
        }
        // 字符全部匹配，再判断是否以该字符结尾
        return temp.isEnd();
    }

    /**
     * Returns if there is any word in the trie that starts with the given prefix.
     */
    public boolean startsWith(String prefix) {
        TrieTree temp = this.root;
        int index;
        for (int i = 0; i < prefix.length(); i++) {
            index = prefix.charAt(i) - 97;
            if (temp.getTrieTrees()[index] == null) {
                // 字符不匹配，或长度不匹配
                return false;
            }
            temp = temp.getTrieTrees()[index];
        }
        return true;
    }

    public static void main(String[] args) {
        Trie trie = new Trie();
        trie.insert("how");
        trie.insert("how");
        trie.insert("hi");
        trie.insert("her");
        trie.insert("se");
        System.out.println(trie.search("ho"));
        System.out.println(trie.search("o"));
        System.out.println(trie.startsWith("ho"));
    }
}

/**
 * TrieTree 只保存小写字符
 */
class TrieTree {

    private char c;

    /**
     * 是否有以这个字符结尾的字符串
     */
    private boolean isEnd = false;

    /**
     * 用来保存小写字符
     */
    private TrieTree[] trieTrees = new TrieTree[26];

    public TrieTree(char charAt) {
        this.c = charAt;
    }

    public TrieTree() {

    }

    public char getC() {
        return c;
    }

    public void setC(char c) {
        this.c = c;
    }

    public boolean isEnd() {
        return isEnd;
    }

    public void setEnd(boolean end) {
        isEnd = end;
    }

    public TrieTree[] getTrieTrees() {
        return trieTrees;
    }

    public void setTrieTrees(TrieTree[] trieTrees) {
        this.trieTrees = trieTrees;
    }
}
